import Web3 from "web3";
import usdtArtifact from "./USDT.json";
/**
 * abi
 * 1.基本转账功能 transfer
 * 2.发行总量查询 totalSupply
 * 3.账户余额查询 balanceOf
 * 4.授权第三方权限 approve
 * 5.调用第三方授权转账 transferFrom
 * 6.授权额度查询 allowance
 * 
 */
/**
 *
 * heco-usdt合约地址
 * 0xa71edc38d189767582c38a3145b5873052c3e47a
 * 0xefb5cbc1AF9E0aEFF044DDAA879c9be49a01E5DC
 * 0x652a71fe217F5D8F25e8257B23b5BE676d6Bd4DE
 * 0x0e842CB174ecd0094Bfa3AA69332bcdCBD97cF5c
 *
 */
const wei2eth = (count) => {
  return count / 1e18;
}
const eth2wei = (count) => {
  return count * 1e18;
}
const App = {
  web3: null,
  account: null,
  meta: null,

  start: async function () {
    const { web3 } = this;

    try {
      // get contract instance
      const usdtAddress = usdtArtifact.address;
      this.meta = new web3.eth.Contract(
        usdtArtifact.abi,
        usdtAddress,
      );
      // get accounts
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];

      this.RefreshBalance();

    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },

  RefreshBalance: async function () {
    const { balanceOf } = this.meta.methods;
    const balance = await balanceOf(this.account).call();
    const count = wei2eth(balance).toFixed(10);
    this.$('cur_balance').innerHTML = count;
  },
  TotalSupply: async function () {
    const { totalSupply } = this.meta.methods;
    const totalSupplyCount = await totalSupply().call();
    const count = wei2eth(totalSupplyCount).toFixed(10);
    this.$('labTotalSupply').innerHTML = count;
  },

  BalanceOf: async function () {
    const { balanceOf } = this.meta.methods;
    const balanceOf_address = this.$('balanceOf_address').value;
    const balanceOf_amount = this.$('balanceOf_amount');
    const balanceOfCount = await balanceOf(balanceOf_address).call();
    const count = wei2eth(balanceOfCount).toFixed(10);
    balanceOf_amount.innerHTML = `${count}`
  },
  Approve: async function () {
    const { approve } = this.meta.methods;
    const approve_adress = this.$('approve_adress').value;
    const approve_amount = (+this.$('approve_amount').value);
    const count = eth2wei(approve_amount);
    const balanceOfCount = await approve(approve_adress, `${count}`).send({ from: this.account });
    alert('授权成功')
  },

  Allowance: async function () {
    const { allowance } = this.meta.methods;
    const allowance_adress = this.$('allowance_adress').value;
    const allowance_amount = this.$('allowance_amount');
    const allowanceCount = await allowance(this.account, allowance_adress).call();
    const count = wei2eth(allowanceCount).toFixed(10);
    allowance_amount.innerHTML = `${count}`;
  },
  Transfer: async function () {
    const { transfer } = this.meta.methods;
    const transfer_amount = this.$('transfer_amount').value;
    let count = eth2wei(transfer_amount);
    const transfer_to = this.$('transfer_to').value;
    await transfer(transfer_to, `${count}`).send({ from: this.account });
    alert('转账成功')
  },

  TransferFrom: async function () {
    const { transferFrom } = this.meta.methods;
    const transferFrom_amount = this.$('transferFrom_amount').value;
    const transferFrom_from = this.$('transferFrom_from').value;
    const transferFrom_to = this.$('transferFrom_to').value;
    let count = eth2wei(+transferFrom_amount)
    await transferFrom(transferFrom_from, transferFrom_to, `${count}`).send({ from: this.account });
    let successInfo = `由 ${this.account} 发起的一笔交易
    from:${transferFrom_from}
    to:${transferFrom_to}
    count:${transferFrom_amount}
    交易成功
    `;
    alert(successInfo)
    console.log(successInfo);
  },
  Random: async function () {
    const { balanceOf } = this.meta.methods;
    const address = this.web3.utils.randomHex(20);
    // const address = '0x0e842CB174ecd0094Bfa3AA69332bcdCBD97cF5c'
    const random_address = this.$('random_address');
    const random_amount = this.$('random_amount');
    const balanceOfCount = await balanceOf(address).call();
    const count = wei2eth(balanceOfCount);
    random_amount.innerHTML = `${count}`
    random_address.innerHTML = `${address}`
    if (count > 0) {
      alert(`{address} usdt: ${count}`)
    }
  },
  $: function (id) {
    return document.getElementById(id);
  }

};

window.App = App;

window.addEventListener("load", function () {
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(
      new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
    );
  }

  App.start();
});
